//index.js
let config=require('../../config.js');
let sort = require('../../util/sort.js');
let uuid = require('../../util/uuid.js');
const icon_err = "/image/err_w.png";
let app = getApp();
Page({
  data:{
    islogined:false,
    account:{},
    userInfo:{},
    filter: "", //搜索联系人条件
    contactsList: [], // 通讯录
    isremember:true
  },
  // 筛选联系人
  inputFilter: function (event) {
    let value = event.detail.value;
    this.setData({
      filter: value
    });
    let contactsList = JSON.parse(JSON.stringify(app.contactsList));
    for (let i = 0; i < contactsList.length; i++) {
      let item = contactsList[i];
      let idx = item.nickName.indexOf(value);
      if (idx == -1) {
        contactsList.splice(i,1);
      }
    }
    this.setData({
      contactsList: contactsList
    });
    return value
  },
  // 跳转到联系人详情页
  showPersonDetail: function (event) {
    // console.log('showPersonDetail', event);
    let args = JSON.stringify(event.currentTarget.dataset);
    wx.navigateTo({
      url: '../unit/userInfo/index?args=' + args
    })
  },
  //账号登陆
  formSubmit:function(){
    // 判断登录信息是否完整
    let login_account = this.data.account;
    if ( !login_account.uname || !login_account.upass){
      wx.showToast({
        title: '请填写完整账号信息',
        image: icon_err,
        mask:true
      })
      return 
    }
    
    // 开始请求登录
    let that=this;
    app.showLoginingToast();
    login_account=JSON.stringify(login_account);
    // console.log("account login", login_account);
    wx.request({
      url: config.loginUrl + 'aclogin.php',
      // url: config.test + 'login/aclogin.php',
      data: {
        account: login_account
      },
      success: function (res) {
        // 请求成功响应
        console.log("account login success", res.data);
        let rdata=res.data;
        if(rdata.stats==0){
          // 显示登录失败原因
          wx.showToast({
            title: rdata.msg,
            image: icon_err,
            // mask: true
          })
          return;
        }

        // 登录成功后的操作
        that.afterlogin(res.data);
        app.showLoginSucToast();

        // 缓存登录账号信息
        let isremember = that.data.isremember;
        if (!isremember){
          login_account = JSON.stringify({
            sysNo: '',
            uname:'',
            upass:''
          })
        }
        wx.setStorage({
          key: "bfdx_login_account",
          data: login_account,
          success: function (res) {
            // console.log("setStorage", res);
          }
        })
      },
      fail:function(res){
        console.log("account login fail", res);
        let title ='登录失败';
        if (res.errMsg.indexOf('timeout')!==-1){
          title='登录超时';
        }
        // 显示登录失败原因
        wx.showToast({
          title: title,
          image: icon_err,
          mask: true
        })
      }
    });
  },
  //使用微信账号登录
  useWxLogin:function(){
    let that=this;
    app.showLoginingToast();
    wx.login({
      success: function(res) {
        // console.log('wx login success',res);
        wx.request({          
          url: config.loginUrl +'wxlogin.php',
          // url: config.test +'login/wxlogin.php',
          data: {
            code: res.code
          },
          success: function (res) {
            console.log("wxlogin session", res.data);
            app.showgetInfoToast();

            let rdata=res.data;
            if (rdata.stats === 0){
              wx.showToast({
                title: rdata.msg,
                icon: "success"
                // mask: true
              })
              return;
            }
            app.ssid = rdata.ssid;
            if(rdata.stats===2){
              // 第一次使用微信登录，需要补充账号资料
              wx.navigateTo({
                url: '/page/unit/signUp/index?usid=' + rdata.usid,
              })
              return;
            }
            // 登录成功
            that.afterlogin(rdata);

            app.showLoginSucToast();
          }
        });
      },
      fail: function(msg) {
        console.log(msg);
        wx.showToast({
          title: '登陆失败',
          image: icon_err,
          mask: true
        })
      }
    });
  },
  // 登录后本页面的操作
  afterlogin:function(data){
    let contactsList = sort(data.userRows, { 'uname': "asc" });
    this.setData({
      contactsList: contactsList,
      islogined: true,
      userInfo: data.self
    })

    // 同步app全局变量数据
    app.afterLogined(data);
  },
    //记住账号
  loginSwitchChange:function(event){
    // console.log("switch", event);
    let login_account = {
      sysNo: "",
      uname: "",
      upass: ""
    };
    if(event.detail.value){
      login_account = this.data.account;
      this.setData({
        isremember:true
      })
    }else{
      this.setData({
        isremember: false
      })
    }
    wx.setStorage({
      key: "bfdx_login_account",
      data: JSON.stringify(login_account),
      success: function (res) {
        // console.log("setStorage", res);
      }
    })

  },
  //双向绑定系统号、账号、密码
  syncInputAccount:function(key,value){
    let account = this.data.account;
    account[key]=value;
    this.setData({
      account: account
    })
    // console.log("account", account);
  },
  inputSysNo:function(event){
    this.syncInputAccount("sysNo", event.detail.value)
  },
  inputLoginName: function (event) {
    this.syncInputAccount("uname", event.detail.value)
  },
  inputLoginPassWord: function (event) {
    this.syncInputAccount("upass", event.detail.value)
  },
  onShow: function () {
    this.setData({
      islogined: app.islogined
    })
  },
  onReady: function (options) {
  },
  onLoad:function(opts){
    // console.log('onload');
    if (app.account) {
      this.setData({
        account: app.account
      })
    } else {
      this.setData({
        account: {
          sysNo: '',
          uname: '',
          upass: ''
        }
      })
    }
  }

})
